<?php
namespace app\admin\controller;
use think\facade\Db;
use app\admin\model\Distributor as DistributorModel;
use app\admin\model\DistributorLevel;
use app\admin\model\User;
use app\common\BaseController;
use hg\apidoc\annotation as Apidoc;
use think\Request;
use think\exception\ValidateException;
use app\common\support\PHPExcelService;

class Distributor extends BaseController{
    

    /**
     * @Apidoc\Title("列表")
     * @Apidoc\Url("Distributor_index")
     * @Apidoc\Method("GET")
     * @Apidoc\Returned("data", type="array", desc="业务数据",replaceGlobal="true",
     *   @Apidoc\Returned("page",type="int",desc="页码"),
     *   @Apidoc\Returned("limit",type="int",desc="查询数量"),
     *   @Apidoc\Returned("data",type="array",desc="返回数据"),
     *   @Apidoc\Returned("total",type="array",desc="数据总量")
     * )
     */
    public function index(Request $request){
        $page  = (int)$request->param('page/d', 0);
        $limit  = (int)$request->param('limit/d', 10);
        $search = request()->param();
        $where = [];
            if(isset($search["name"]) && $search["name"]!="") $where[] = ["name","=",$search["name"]];
            if(isset($search["mobile"]) && $search["mobile"]!="") $where[] = ["mobile","=",$search["mobile"]];
            if(isset($search["status"]) && $search["status"]!="") $where[] = ["status","=",$search["status"]];
            if(isset($search["balance"]) && $search["balance"]!="") $where[] = ["balance","=",$search["balance"]];

        $query  = DistributorModel::where($where);
        $total  = $query->count();
        $data   = $query->page($page,$limit)->order('id desc')->append(['status_name'])->select();
        return $this->success('', [
            'start' => $page,
            'limit' => $limit,
            'data'  => $data,
            'total' => $total,
        ]);
    }

    
        /**
     * @Apidoc\Title ("详情")
     * @Apidoc\Url("Distributor_get")
     * @Apidoc\Method("GET")
     * @Apidoc\Param("id", type="int", require=true, desc="id")
     * @Apidoc\Returned("data", type="array", desc="业务数据",replaceGlobal="true",
     *   @Apidoc\Returned("data",type="string",desc="信息")
     * )
     */
    public function detail(int $id): \think\response\Json
    {
        try {
            $row  = DistributorModel::where('id', $id)->find();
        } catch (DataNotFoundException | ModelNotFoundException | DbException $e) {
            return $this->error($e->getMessage());
        }

        return $this->success('', $row);
    }

    /**
     * @Apidoc\Title("创建")
     * @Apidoc\Url("Distributor_create")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("field1", type="string", require=false, desc="field1")
     * @Apidoc\Param("field2", type="string", require=false, desc="field2")
     * @Apidoc\Param("field3", type="string", require=false, desc="field3")
     */
       public function create(Request $request): \think\response\Json
    {
        $data = $request->post();
        $data['status'] = 1;
        try {
            $this->validate($data, [
                'name' => 'require',
                'mobile' => 'require',
            ], [
               'name.require'  => '姓名不得为空',
               'mobile.require'  => '手机号不得为空'
            ]);
        } catch (ValidateException $e) {
            return $this->error($e->getError());
        }
        if(DistributorModel::where('mobile',$data['mobile'])->count())  return $this->error('该手机号已存在');
        $result = DistributorModel::create($data);
        if ($result->isEmpty()) {
            return $this->error('错误');
        }

        return $this->success('成功');
    }



    /**
     * @Apidoc\Title("编辑")
     * @Apidoc\Url("Distributor_edit")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("field1", type="string", require=false, desc="field1")
     * @Apidoc\Param("field2", type="string", require=false, desc="field2")
     * @Apidoc\Param("field3", type="string", require=false, desc="field3")
     */
    public function edit(){
        $data = request()->post();
        unset($data['status']);
         try {
            $this->validate($data, [
                'id' => 'require',
                'name' => 'require',
                'mobile' => 'require'
            ], [
                'id.require'  => '主键必须',
                'name.require'  => '姓名不得为空',
                'mobile.require'  => '手机号不得为空'
            ]);
        } catch (ValidateException $e) {
            return $this->error($e->getError());
        }
        if(DistributorModel::where('mobile',$data['mobile'])->where('id','<>',$data['id'])->count())  return $this->error('该手机号已存在');
        if(DistributorModel::update($data,['id'=>$data['id']])) return $this->success('操作成功');
        return $this->error('操作失败');
    }





        /**
     * @Apidoc\Title ("删除")
     * @Apidoc\Url("Distributor_delete")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("id", type="int", require=true, desc="id")
     */
    public function delete(): \think\response\Json
    {
        $ids = request()->post('ids/s');
        $ids = explode(',', $ids);
        $row = DistributorModel::where('id','in', $ids)->select();
        if (!$row) {
            return $this->error('错误');
        }
        $row->delete();
        return $this->success('成功');
    }

    
        /**
     * @Apidoc\Title ("审核通过")
     * @Apidoc\Url("Distributor_yes")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("id", type="int", require=true, desc="id")
     */
    public function yes(): \think\response\Json
    {
        Db::startTrans();
        try {
            $ids = request()->post('ids');
            $row = DistributorModel::where('id', $ids)->find();
            if (!$row) {
                return $this->error('无此信息');
            }
            DistributorModel::where('id', $ids)->update(['status'=>1]);
            if($row->uid){
                User::where('id',$row->uid)->update(['did'=>$ids]);
            }else{
                User::where('mobile',$row->mobile)->where('did',0)->update(['did'=>$ids]);
            }
           
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
             return $this->error($e->getMessage());
        }
       
        return $this->success('成功');
    }

    /**
     * 审核拒绝
     */
    public function no(): \think\response\Json
    {
        Db::startTrans();
        try {
            $ids = request()->post('ids');
            $row = DistributorModel::where('id', $ids)->find();
            $user = User::where('id',$row->uid)->find();
            if($user->did > 0) return $this->error('该用户已绑定分销员');
            if (!$row) {
                return $this->error('无此信息');
            }
            DistributorModel::where('id', $ids)->update(['status'=>2]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
             return $this->error($e->getMessage());
        }
       
        return $this->success('成功');
    }

    //导出
     public function export_excell(){
        $search = request()->param();
        $where = [];
           if(isset($search["name"]) && $search["name"]!="") $where[] = ["name","=",$search["name"]];
            if(isset($search["mobile"]) && $search["mobile"]!="") $where[] = ["mobile","=",$search["mobile"]];

            if(isset($search["status"]) && $search["status"]!="") $where[] = ["status","=",$search["status"]];
            if(isset($search["balance"]) && $search["balance"]!="") $where[] = ["balance","=",$search["balance"]];

        $query  = DistributorModel::where($where);
        big_array_to_csv($query,'data.csv',[]);
    }



        /**
     * 导入
     * @return void
     * @author Sam
     */
    public function import_excell(){
        if(empty($_FILES['file'])) json_response(0, '请选择文件');
        $list = big_csv_to_array($_FILES['file']['tmp_name']);
        try{
            $num = 0;
            if(count($list)){
                foreach($list as $k=>$v){
                    $data = [
                        'create_time'=>time(),
                        'update_time'=>time(),
                    ];
                $res =  DistributorModel::create($data);
                if($res) $num++;
                }
            }
                return  $this->success('导入成功'.$num.'条数据');
            }catch(\Exception $e){
                return $this->error($e->getMessage());
            }
        }
}